package org.oexam.ostudy.db;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import javax.naming.NamingException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.oexam.ostudy.misc.GeneralConstants;
import org.oexam.ostudy.struct.Announcements;
import org.oexam.ostudy.struct.General_announcementsList;

public class GeneralAnnoucementsAccess {

	/**
	 * @uml.property name="table_name"
	 */
	private String table_name = "Announcements";

	// This method uses JDBC and should be used only when hibernate is not
	// available.
	public General_announcementsList getAllHeadlines() throws SQLException,
			NamingException {

		General_announcementsList gheadLines = new General_announcementsList();

		DBConnection dbConnection = new DBConnection();

		ResultSet rs = dbConnection
				.executeQuery(GeneralConstants.select_all_sql + table_name);

		while (rs.next()) {
			gheadLines.setHeadLine(rs.getString("id"),
					rs.getString("Announcement"));
		}
		rs.close();

		return gheadLines;

	}

	public int getLastAnnID() throws SQLException, NamingException {

		DBConnection dbConnection = new DBConnection();

		ResultSet rs = dbConnection.executeQuery("select max(id) as id from Announcements");

		int lastId = 0;
		while (rs.next()) {
			lastId = Integer.parseInt(rs.getString("id"));

		}
		rs.close();

		return lastId;

	}

	public String insertAnnouncement(String ann) throws SQLException, NamingException {
		
		SessionFactory sf = new Configuration().configure()
				.buildSessionFactory();

		Session session = sf.openSession();

		session.beginTransaction();
		
		Announcements announcement = new Announcements();
		announcement.setId(this.getLastAnnID()+1);
		announcement.setAnn_date(new Date());
		announcement.setAnnouncement(ann);
		
		session.save(announcement);
		
		session.getTransaction().commit();
		session.close();

		return "ok";
	}

}
